<?php

/* custom searchform */
function mkt_searchform() {
    return '<form role="search" method="get" class="mkt-searchform" id="searchform" action="' . esc_url(home_url('/')) . '">
        <div>
            <input type="text" class="mkt-searchquery" value="' . get_search_query() . '" name="s" id="s" placeholder="' . __('Search', 'woocommerce') . '" />
            <button type="submit" class="mkt-searchsubmit" id="searchsubmit"><i class="fa fa-search"></i></button>
            <input type="hidden" name="post_type" value="product" />
        </div>
    </form>';
}
add_action('get_product_search_form', 'mkt_searchform');

/* ---------- products list -------------*/
/* dont display order */
remove_action('woocommerce_before_shop_loop', 'woocommerce_result_count', 20);
remove_action('woocommerce_before_shop_loop', 'woocommerce_catalog_ordering', 30);

/* dont display sale flash */
remove_action('woocommerce_before_shop_loop_item_title', 'woocommerce_show_product_loop_sale_flash', 10);

/* ------------ product single --------------*/
/* dont display sale flash */
remove_action('woocommerce_before_single_product_summary', 'woocommerce_show_product_sale_flash', 10);

/* remove price */
remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_price', 10);

/* remove product meta */
remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_meta', 40);

/* remove product sharing */
remove_action('woocommerce_single_product_summary', 'woocommerce_template_single_sharing', 50);

/* remove reviews tab */
add_filter('woocommerce_product_tabs', 'mkt_woo_remove_reviews_tab', 98);

function mkt_woo_remove_reviews_tab($tabs) {
    unset($tabs['reviews']);
    return $tabs;
}

/* text search with attribute */
function mkt_custom_search_query($where) {
    if (!is_admin() && is_search()) {
        global $wpdb;
        $query = get_search_query();
        $query = like_escape( $query );
        
        /* filter woocommerce attributes with name like query */
        
        $attribute_taxonomies = wc_get_attribute_taxonomies();
        $taxonomy_terms = array();

        if ($attribute_taxonomies) :
            foreach ($attribute_taxonomies as $tax) :
                if (taxonomy_exists(wc_attribute_taxonomy_name($tax->attribute_name))) :
                    $taxonomy_terms[$tax->attribute_name] = get_terms(wc_attribute_taxonomy_name($tax->attribute_name), array('name__like' => $query));
                endif;
            endforeach;
        endif;
        
        /* if have attributes, add an OR condition get products belong to these attributes */
        if (count($taxonomy_terms) > 0) {
            foreach ($taxonomy_terms as $term) {
                
                if ($term[0]) {
                   
                   $where .=" OR {$wpdb->posts}.ID IN (SELECT {$wpdb->posts}.ID FROM {$wpdb->posts},{$wpdb->term_relationships},{$wpdb->terms} WHERE {$wpdb->posts}.ID = {$wpdb->term_relationships}.object_id AND {$wpdb->term_relationships}.term_taxonomy_id = {$wpdb->terms}.term_id AND {$wpdb->terms}.term_id = ".$term[0]->term_taxonomy_id.")";
                }
            }
        }
        $where .=" OR {$wpdb->posts}.ID IN (SELECT {$wpdb->posts}.ID FROM {$wpdb->posts},{$wpdb->postmeta} WHERE {$wpdb->posts}.ID = {$wpdb->postmeta}.post_id AND {$wpdb->postmeta}.meta_key = '_mkt_custom_att_keyword' AND {$wpdb->postmeta}.meta_value LIKE '%".$query."%')";
    }
    
    return $where;
}
add_filter('posts_where', 'mkt_custom_search_query');

/* 
 * update attributes hook
 * if a product has custom attributes that are not taxonomy, create new post_meta for searching
 *  */
add_action( 'updated_post_meta', 'mkt_product_custom_attributes', 10, 4 );
function mkt_product_custom_attributes( $meta_id, $post_id, $meta_key, $meta_value ) {
    if ( '_product_attributes' == $meta_key ) {
        $custom_att_arr = array();
        foreach ($meta_value as $meta) {
            // $meta has name, value, position, is_visible, is_variation, is_taxonomy
            if ($meta['value'] != '') {
                $custom_att_arr[] = $meta['value'];
            }
        }
        $custom_att_keyword = implode(',', $custom_att_arr);
        update_post_meta($post_id, '_mkt_custom_att_keyword', $custom_att_keyword);
    }
}

function mkt_output_random_all_products() {
    $args = array(
        'posts_per_page' => 4,
        'columns' => 4,
        'orderby' => 'rand'
    );

    $args = wp_parse_args( $args );

    wc_get_template( 'single-product/all_random.php', $args );
}

/**
 * Override current sumbol
 * @param $currency_symbol
 * @param $currency
 *
 * @return string
 */
function mkt_single_product_currency_symbol($currency_symbol, $currency) {
    return '<span class="symbol">'.$currency_symbol.'</span>';
}

/* Add more suffix in single product */
function mkt_add_more_price_suffix($suffix, $this) {
    $link = get_permalink( get_page_by_path('mkt-versand' ));
    $text = 'zzgl. <a href="'.$link.'">'.__('Versandkosten', 'mkt').'</a>';
    $more = '<small class="woocommerce-price-suffix">' . $text . '</small>';

    return $suffix.$more;
}

/**
 * Get body class for template
 * @return string
 */
function mkt_get_body_class() {
    $body_class= '';
    if(is_single()) {
        $body_class = 'single-page';
    }
    elseif(is_archive()) {
        $body_class = 'archive-page';
    }
    elseif(is_page()) {
        $body_class = 'page-page';
    }

    return $body_class;
}

/**
 * Override availability of product! - managing_stock depend on local config at products
 *
 * @param $arr
 * @param $obj
 *
 * @return array
 */
function mkt_woocommerce_get_availability($arr, $obj) {
    if(!$obj->managing_stock() && $obj->is_in_stock()) {
        $availability = __( 'In stock', 'woocommerce' );
        $class        = 'in-stock';
        return array( 'availability' => $availability, 'class' => $class );
    }

    return $arr;
}

// Display Fields using WooCommerce Action Hook
add_action( 'woocommerce_product_options_general_product_data', 'mkt_general_product_data_custom_field' );
function mkt_general_product_data_custom_field() {
    global $woocommerce, $post;
    echo '<div class="options_group">';
    woocommerce_wp_checkbox(
        array(
            'id' => '_e_commingsoon',
            'wrapper_class' => 'checkbox_class',
            'label' => __('Comming soon', 'mkt' ),
            'description' => __( 'Is product comming soon ?', 'mkt' )
        )
    );
    echo '</div>';
}

// Save Fields using WooCommerce Action Hook
add_action( 'woocommerce_process_product_meta', 'mkt_process_product_meta_fields_save' );
function mkt_process_product_meta_fields_save( $post_id ){
    $woo_checkbox = isset( $_POST['_e_commingsoon'] ) ? 'yes' : 'no';
    update_post_meta( $post_id, '_e_commingsoon', $woo_checkbox );
}

/* change number post_per_page upsell on single product */
function mkt_upsells_post_per_page($post_per_page) {
    return -1;
}